package postgres

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"gorm.io/gorm"
	logger "ota/collector/logger"
	"ota/config"
	"ota/errors"
	"ota/model"
	"ota/model/entity"
	"ota/utils"
)

var Firmware = &firmware{&execTx{}}

type firmware struct {
	IExecTx
}

func init() {
	Register(Firmware)
}

func (a *firmware) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.Firmware{}
		if dbOta.Migrator().HasTable(p) {
			logger.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := dbOta.AutoMigrate(p); err != nil {
			logger.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			logger.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *firmware) Create(ctx context.Context, m *entity.Firmware) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

func (a *firmware) FindDetail(ctx context.Context, in *model.FirmwareInfoRequest) (*model.FirmwareDetailInfo, error) {

	var (
		e        = &model.FirmwareDetailInfo{}
		subQuery = GetDB(ctx).Model(&entity.FirmwareType{}).ToSQL(func(tx *gorm.DB) *gorm.DB {
			return tx.
				Select("json_agg(json_build_object('id', firmware_type.id, 'name', firmware_type.name))").
				Where("firmware_type.id = ANY (firmware.type_ids)").Find(&entity.FirmwareType{})
		})
	)

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}

	q := GetDB(ctx).
		Model(&entity.Firmware{}).
		Select(
			"firmware.*",
			fmt.Sprintf("(%v) as types", subQuery)).
		Where("id", in.Id)

	err := q.First(&e, in.Id).Error
	return e, err
}

// Find detail
func (a *firmware) Find(ctx context.Context, in *model.FirmwareInfoRequest) (*entity.Firmware, error) {
	e := &entity.Firmware{}

	q := GetDB(ctx).Model(&entity.Firmware{})

	if in.Id == 0 {
		return e, errors.New("condition illegal")
	}

	err := q.First(&e, in.Id).Error
	return e, err
}

// Update
func (a *firmware) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.Firmware{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *firmware) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.Firmware{}, id).Error
}

// List query list
func (a *firmware) List(ctx context.Context, in *model.FirmwareListRequest, opts ...model.QueryOptions) (int, []*model.FirmwareDetailInfo, error) {
	var (
		opt       = model.GetQueryOption(opts...)
		q         = GetDB(ctx).Model(&entity.Firmware{})
		err       error
		total     int64
		firmwares []*model.FirmwareDetailInfo
		subQuery  = GetDB(ctx).Model(&entity.FirmwareType{}).ToSQL(func(tx *gorm.DB) *gorm.DB {
			return tx.
				Select("json_agg(json_build_object('id', firmware_type.id, 'name', firmware_type.name))").
				Where("firmware_type.id = ANY (firmware.type_ids)").Find(&entity.FirmwareType{})
		})
	)

	q = q.Select(
		"firmware.*",
		fmt.Sprintf("(%v) as types", subQuery))

	if in.Id != nil {

		q = q.Where("id = ?", in.Id)

	}

	if in.Ids != nil {

		q = q.Where("id IN ?", in.Ids)

	}

	if in.TypeIds != nil {

		q = q.Where("type_ids = ?", in.TypeIds)

	}

	if in.Name != nil {

		q = q.Where("name like ?", utils.SqlLike(in.Name))

	}

	if in.FileSize != nil {

		q = q.Where("file_size = ?", in.FileSize)

	}

	if in.Description != nil {

		q = q.Where("description like ?", utils.SqlLike(in.Description))

	}

	if in.Version != nil {

		q = q.Where("version like ?", utils.SqlLike(in.Version))

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if len(opt.SelectFields) > 0 {
		q = q.Select(opt.SelectFields)
	}

	if len(opt.OrderFields) > 0 {
		q = q.Order(fmt.Sprintf("%v", model.ParseOrder(opt.OrderFields)))
	}

	b := !opt.OnlyCount && !opt.OnlyList
	if opt.OnlyCount || b {
		if err = q.Count(&total).Error; err != nil {
			return 0, nil, err
		}
	}
	if opt.OnlyList || b {
		if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&firmwares).Error; err != nil {
			return 0, nil, err
		}
	}
	return int(total), firmwares, nil
}

// ExecTransaction execute database transaction
func (a *firmware) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
